<template>
  <div v-loading="loading" class="readOver">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col v-if="isDeal" :span="12">
          <el-form-item :label="$t('项目名称')" prop="dealId">
            <el-select v-model="form.dealId" :placeholder="$t('项目')" filterable class="select-btn" style="width: 200px;flex-shrink: 0;" @change="changeDeal($event); queryPlan">
              <el-option
                v-for="item in dealList"
                :key="item.id"
                :value="item.id"
                :label="item.dealName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('创建人')" prop="user.userId">
            <UserSelect
              v-model="form.user.userId"
              :placeholder="$t('创建人')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('发生时间')" prop="happenTime">
            <DatePicker v-model="form.happenTime" :placeholder="$t('发生时间')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('事项类型')" prop="itemType">
            <dictSelect
              ref="dict"
              v-model="form.itemType"
              :clearable="true"
              dictionary="item_type"
              :is-check="true"
              @change="onchange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('跟踪方式')" prop="trackMode">
            <dictSelect
              v-model="form.trackMode"
              :clearable="true"
              dictionary="track_mode"
              :is-check="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('关注等级')" prop="levelConcern">
            <el-select v-model="form.levelConcern" :placeholder="$t('关注等级')" clearable>
              <el-option
                v-for="dict in levelConcernOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('对方人员')" prop="otherPeople">
            <el-input v-model="form.otherPeople" maxlength="120" show-word-limit :placeholder="$t('对方人员')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('项目计划')" prop="dealSuperviseId">
            <el-select v-model="form.dealSuperviseId" clearable :placeholder="$t('项目计划')">
              <el-option
                v-for="item in dealSuperviseOptions"
                :key="item.id"
                :value="item.id"
                :label="item.itemName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('工作量(人天)')" prop="workload">
            <el-input-number v-model="form.workload" :min="0" :max="1000000" :controls="false" :precision="0" :placeholder="$t('工作量(人天)')" />
          </el-form-item>
        </el-col>
        <el-col v-for="(item,index) in form.fields" :key="index" :span="24">
          <el-form-item :label="$t(item.fieldLabel)" :prop="item.fieldName">
            <EditorTxt v-model="(form.fields)[index].content" :height="300" />
          <!--            <el-input v-model="form.details" type="textarea" :autosize="{ minRows: 6 }" maxlength="2000" show-word-limit :placeholder="$t('详细情况')" />-->
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('详细情况')" prop="details" :rules="[{required: hasWeeklyApp && form.syncWeekly === '1',message:$t('必填信息'),trigger:'blur'}]">
            <!--<EditorTxt v-model="form.details" :height="400" :placeholder="$t('详细情况')" />-->
            <!--            <el-input v-model="form.details" type="textarea" :autosize="{ minRows: 6 }" maxlength="2000" show-word-limit :placeholder="$t('详细情况')" />-->
            <EditorTxt v-if="!loading" ref="editorTxt" :key="form.id" v-model="form.details" :height="300" :placeholder="$t('详细情况')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('下一步计划')" prop="nextStepPlan">
            <EditorTxt v-if="!loading" v-model="form.nextStepPlan" :height="300" :placeholder="$t('下一步计划')" />
          <!--            <el-input v-model="form.nextStepPlan" type="textarea" :autosize="{ minRows: 6 }" maxlength="2000" show-word-limit :placeholder="$t('下一步计划')" />-->
          </el-form-item>
        </el-col>
      </el-row>
      <FileTable :list.sync="form.fileList" has-permi="deal:track" data-type="deal_track" :business-id="form.dealId" :btn-show="!btnHide" />
    </el-form>

    <!-- 跟踪的消息评论 -->
    <div v-if="form.id !== undefined && form.id !== null && form.id !== '' && form.msgBaseList !== null && form.msgBaseList.length > 0" class="dealTrackMsg">
      <dealTrackMsg ref="dealTrackMsg" :form-data="form" />
    </div>
    <div v-if="!btnHide" slot="footer" :style="{'padding-bottom':isError ? '15px' : ''}" class="dialog-footer cycle" :class="dealClass" style="text-align: right;">
      <el-switch v-if="!form.id && hasWeeklyApp" v-model="form.syncWeekly" active-text="同步周会看板" active-value="1" inactive-value="0" style="margin-right: 10px;" @change="onChangeSwitch">{{ $t('同步周会看板') }}</el-switch>
      <span style="position: relative">
        <el-date-picker
          v-if="!form.id && hasWeeklyApp && form.syncWeekly === '1'"
          v-model="form.cycle"
          :class="isError ? 'is-error' : ''"
          type="week"
          :picker-options="{firstDayOfWeek: 1}"
          :format="getWeekDescription(new Date(form.cycle))"
          value-format="yyyy-MM-dd"
          :clearable="false"
          placeholder="选择周"
          size="small"
          style="width: 120px"
          @change="changeDate"
        />
        <span v-if="isError" style="display: inline-block;position: absolute;bottom: -28px;font-size: 12px;color: red;left: 0;text-align: left;width: 100%">必填信息</span>
      </span>
      <!--保存，保存并启动流程，取消 三个按钮-->
      <SaveBtn has-permi="deal:track" />
    </div>
  </div>
</template>

<script>
import { findDealLimit } from '@/api/base/deal/dealBase'
    import { saveDealTrack, getDealTrack } from '@/api/deal/track/dealTrack'
    import { findListSupervise } from '@/api/deal/supervise/dealSupervise'
    import EditorTxt from '@/components/Tinymce'
    import dealTrackMsg from '@/views/deal/dealTrack/dealTrackMsg'
    import { mapState } from 'vuex'
    import { getDealBase } from '@/api/base/deal/dealBase'
    import { getWeekDescription } from '@/utils/ruoyi'
    export default {
      components: {
        EditorTxt,
        dealTrackMsg
      },
      props: {
        dealId: {
          type: String,
          default: undefined
        },
        isDeal: {
          type: Boolean,
          default: true
        }
      },
        data() {
            return {
                otherBtnHide: false,
                // 事项类型 字典item_type字典
                itemTypeOptions: [], // 跟踪方式 字典track_mode字典
                trackModeOptions: [], // 表单参数
                // 是否显示MainBodySelect组件
                dealList: [],
                dealIdList: [],
                form: {
                  fileList: [],
                  user: {
                    userId: undefined
                  },
                  syncWeekly: '1'
                },
                // 是否隐藏保存等按钮
                btnHide: false,
                // 遮罩层
                loading: true,
                isError: false,
                // 表单校验
                rules: {
                  dealId: [
                    { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                  ],
                  cycle: [
                    { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                  ],
                  'user.userId': [
                    { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                  ],
                  happenTime: [
                    { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                  ],
                  itemType: [
                    { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                  ],
                  trackMode: [
                    { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                  ],
                  levelConcern: [
                    { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                  ],
                  details: [
                    { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                  ]
                },
                dealSuperviseOptions: [],
                levelConcernOptions: [],
                saveField: undefined,
                saveFieldData: [],
                dealClass: '',
                sourcePage: ''
            }
        },
      computed: {
        ...mapState({
          hasWeeklyApp: state => state.marketApp.hasWeeklyApp
        })
      },
        created() {
          this.$bus.$emit('async_done')
          // 关注等级
          this.getDicts('level_concern').then(response => {
            this.levelConcernOptions = response.data
          })
          this.getDealList()
        },
        methods: {
          getDealList() {
            const queryDeal = {
              pageSize: 30,
              pageNum: 1,
              dealIdList: this.dealIdList
            }
            findDealLimit(queryDeal).then(response => {
              this.dealList = (response.rows === null ? [] : response.rows)
            }).catch(() => {
            })
          },
          getWeekDescription,
            // 初始化数据
            init(data) {
                if (!data) { this.dealClass = 'allRightBtn' }
                this.loading = true
                if (data != null && data.id !== undefined) {
                  this.dealClass = ''
                    getDealTrack(data.id).then(response => {
                        this.form = response.data
                        this.saveField = response.data.itemType
                        this.saveFieldData = response.data.fields
                        if (data.sourcePage === 'msgBase') {
                          this.sourcePage = data.sourcePage
                          this.form.msgBaseList = []
                        }
                        console.log('11111111111111111')
                        this.initSuperviseOption()
                    })
                } else {
                  this.reset()
                  if (data) {
                    this.form.dealId = data.dealId
                  }
                  if (this.dealId) {
                    this.form.dealId = this.dealId
                  }
                  // 自动加载关注等级
                  this.changeDeal(this.form.dealId)
                  this.initSuperviseOption()
                }
            },
            initDealIdList(dealIdList) {
              this.dealIdList = dealIdList
              this.getDealList()
            },
          changeDate() {
            if (this.form.cycle) {
              this.isError = false
            }
          },
          initSuperviseOption() {
            // 获取当前项目下的 项目计划
            findListSupervise({ dealId: (this.$route.query.id === undefined) ? this.form.dealId : this.$route.query.id }).then(response => {
              this.dealSuperviseOptions = response.rows
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          },
          onChangeSwitch() {
            if (this.form.syncWeekly === '0') {
              this.form.cycle = undefined
              this.isError = false
            }
          },
          // 初始化数据
          remindersInit(data) {
            this.loading = true
            this.reset()
            if (data != null) {
              this.form.dealId = data.dealId
              this.loading = false
            }
          },
          // 获取字典
          onchange(e) {
              console.log(e)
            if (e === this.saveField && this.saveFieldData && this.saveFieldData.length > 0) {
              this.form.fields = this.saveFieldData
              return
            }
            this.form.fields = []
            var dict = this.$refs.dict.currentDict
            if (dict && dict.childDict) {
              // 获取字段展示
              this.getDicts(dict.childDict).then(res => {
                res.data.content = undefined
                res.data.fieldName = undefined
                res.data.forEach(item => {
                  item.content = undefined
                  item.fieldName = item.dictValue
                  item.fieldLabel = item.dictLabel
                  item.id = undefined
                })
                this.form.fields = res.data
              })
            }
          },

          // 表单重置
            reset() {
              this.form = {
                id: undefined,
                user: {
                  userId: this.$store.state.user.userId
                },
                syncWeekly: '1',
                dealId: undefined,
                happenTime: new Date(),
                itemType: undefined,
                trackMode: undefined,
                levelConcern: undefined,
                otherPeople: undefined,
                dealSuperviseId: undefined,
                workload: undefined,
                details: undefined,
                nextStepPlan: undefined,
                fileList: [],
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined,
                fields: [],
                cycle: undefined
              }
              this.resetForm('form')
            },
            // 取消按钮
            cancel() {
              if (this.$parent.$parent.formOpen !== undefined) {
                this.$parent.$parent.formOpen = false
              }
              if (this.$parent.$parent.reset !== undefined) {
                this.$parent.$parent.reset()
              }
              if (this.isDeal) {
                   this.$parent.$parent.trackFormOpen = false
              }
            },
            // 关闭form页面
            closeForm() {
              // 关闭form页面遮罩层
              this.loading = false
              // 关闭form页面
              if (this.$parent.$parent.formOpen !== undefined) {
                this.$parent.$parent.formOpen = false
              }
              // 刷新list页面
              if (this.$parent.$parent.getList !== undefined) {
                this.$parent.$parent.getList()
                this.$parent.$parent.$parent.$parent.getList()
              }
            },
            /** 提交按钮 */
            submitForm: function() {
              return new Promise((resolve, reject) => {
                this.$refs['form'].validate(valid => {
                  if (this.form.syncWeekly === '1' && this.hasWeeklyApp && !this.form.id) {
                    if (!this.form.cycle) {
                      this.isError = true
                      this.locationError(document)
                      return
                    }
                  }
                  if (valid) {
                    this.loading = true
                    saveDealTrack(this.form).then(response => {
                        if (response.code === 200) {
                            this.msgSuccess(this.$t('保存成功'))
                            this.closeForm()
                            resolve()
                        } else {
                            this.msgError(response.msg)
                            this.loading = false
                            reject()
                        }
                    }).catch(() => {
                      this.loading = false
                    })
                  } else {
                    this.locationError(document)
                    reject()
                  }
                })
              })
            },
            queryPlan(val) {
                  // 获取当前项目下的 项目计划
                findListSupervise({ dealId: val }).then(response => {
                    this.dealSuperviseOptions = response.rows
                })
           },
          changeDeal(dealId) {
              if (dealId) {
                getDealBase(dealId).then(response => {
                  this.form.levelConcern = response.data && response.data.levelConcern
                })
              }
          }
        }

    }
</script>
<style lang="scss" scoped>

.readOver{
  display: flex;
  .dataForm{
    position: unset!important;
    padding: 20px !important;
    height: calc(100% - 67px)!important;
  }
  .dealTrackMsg{
    width: 500px;
    min-width: 500px;
    background: #f7f8fa;
  }
}
.dialog-footer{
  right: 520px!important;
  bottom: 15px!important;
}
.dialog-footer.allRightBtn{
  right: 20px!important;
}

/deep/.cycle .is-error .el-input__inner {
  border-color: red;
}
</style>
